import Realm from 'realm'
import {UserSchema} from "./model/User";
import {BannerSchema} from "./model/Banner";
import {BoutiquesSchema} from "./model/Boutiques";
import {ProductSchema} from "./model/Product";
import {SpecialSchema} from "./model/Special";
import {CategorySchema} from "./model/Category";
import {ProductCategoryRelationSchema} from "./model/ProductCategoryRelation";
//先从本地数据库中查询出数据作为state更新UI然后异步action请求服务器获取新数据
//响应请求后异步更新数据库数据,同步更新UI的state为服务器数据

function createRealmInstance(update: boolean = false): Realm {
    const models = [UserSchema, BannerSchema, BoutiquesSchema, ProductSchema, SpecialSchema, CategorySchema, ProductCategoryRelationSchema];
    const currentVersion = Realm.schemaVersion(Realm.defaultPath) || 0;//获取当前数据库的版本

    if (update) {
        return new Realm({
            schema: models,
            schemaVersion: 2,
            migration: (oldRealm, newRealm) => {
            }
        });//创建新版本并覆盖旧版本 ,模型数据不会丢失，把表结构里的字段更换为其他类型属性时 旧模型的该字段会初始化,

    }
    return new Realm({schema: models, schemaVersion: currentVersion})//生成多张表的数据库结构(会自动加载以前存储的数据)
}

export const realm = createRealmInstance(true);
